<template>
  <view class="customer-service">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left" @click="goBack">
        <u-icon name="arrow-left" size="20" color="#333"></u-icon>
      </view>
      <view class="navbar-center">
        <text class="navbar-title">平台客服</text>
        <text class="navbar-status" :class="{ 'online': isOnline }">
          {{ isOnline ? '在线' : '离线' }}
        </text>
			</view>
			<view class="navbar-right">
        <u-icon name="more-dot-fill" size="20" color="#333" @click="showOptions"></u-icon>
			</view>
		</view>
		
    <!-- 聊天消息区域 -->
		<scroll-view 
      class="chat-container" 
			scroll-y="true" 
			:scroll-top="scrollTop"
      :scroll-into-view="scrollIntoView"
			@scrolltoupper="loadMoreMessages"
		>
			<!-- 加载更多提示 -->
      <view v-if="isLoading" class="loading-tip">
        <u-loading-icon mode="spinner" size="20"></u-loading-icon>
        <text>加载中...</text>
			</view>
			
      <!-- 消息列表 -->
			<view class="message-list">
				<view 
					v-for="(message, index) in messageList" 
          :key="message.id"
          :id="`msg-${message.id}`"
					class="message-item"
          :class="{ 'message-self': message.isSelf }"
				>
					<!-- 头像 -->
          <view class="avatar">
            <image 
              :src="message.isSelf ? userAvatar : serviceAvatar" 
              class="avatar-img"
            ></image>
					</view>
					
					<!-- 消息内容 -->
					<view class="message-content">
						<view class="message-bubble">
							<text class="message-text">{{ message.content }}</text>
						</view>
            <view class="message-time">{{ formatTime(message.timestamp) }}</view>
          </view>
						</view>
					</view>
					
      <!-- 输入提示 -->
      <view v-if="isTyping" class="typing-indicator">
        <text>客服正在输入...</text>
			</view>
		</scroll-view>
		
		<!-- 输入区域 -->
		<view class="input-area">
      <view class="input-container">
				<input 
          v-model="inputMessage" 
					class="message-input" 
          placeholder="请输入您的问题..."
          :disabled="false"
					@confirm="sendMessage"
          @input="onInput"
        />
        <view class="input-actions">
          <view class="action-btn" @click="showAttachment">
            <u-icon name="plus" size="20" color="#666"></u-icon>
			</view>
			<view 
				class="send-btn" 
            :class="{ 'disabled': !canSend }"
				@click="sendMessage"
			>
            发送
          </view>
			</view>
		</view>
    </view>

    <!-- 附件选择弹窗 -->
    <u-popup v-model="showAttachmentPopup" mode="bottom">
      <view class="attachment-popup">
        <view class="attachment-title">选择附件</view>
        <view class="attachment-options">
          <view class="attachment-option" @click="chooseImage">
            <u-icon name="photo" size="30" color="#007AFF"></u-icon>
            <text>图片</text>
          </view>
          <view class="attachment-option" @click="chooseFile">
            <u-icon name="file-text" size="30" color="#34C759"></u-icon>
            <text>文件</text>
          </view>
        </view>
        <view class="attachment-cancel" @click="showAttachmentPopup = false">
          取消
        </view>
      </view>
    </u-popup>

    <!-- 选项弹窗 -->
    <u-popup v-model="showOptionsPopup" mode="bottom">
      <view class="options-popup">
        <view class="option-item" @click="clearHistory">
          <u-icon name="trash" size="20" color="#FF3B30"></u-icon>
          <text>清空聊天记录</text>
        </view>
        <view class="option-item" @click="exportChat">
          <u-icon name="download" size="20" color="#007AFF"></u-icon>
          <text>导出聊天记录</text>
        </view>
        <view class="option-item" @click="showOptionsPopup = false">
          <text>取消</text>
        </view>
      </view>
    </u-popup>
	</view>
</template>

<script>
import { customerServiceApi } from '@/utils/customerServiceApi.js'

	export default {
  name: 'CustomerService',
		data() {
			return {
      isOnline: true,
      messageList: [],
				inputMessage: '',
				scrollTop: 0,
      scrollIntoView: '',
				isLoading: false,
      isTyping: false,
      showAttachmentPopup: false,
      showOptionsPopup: false,
      userAvatar: '/static/profile/avatar.png',
      serviceAvatar: '/static/icons/customer-service.png',
      sessionId: '',
      typingTimer: null,
      page: 1,
      pageSize: 20
    }
  },
  
  computed: {
    canSend() {
      return this.inputMessage.trim() && true
    }
  },
  
  onLoad(options) {
    this.initChat()
  },
  
  onShow() {
    this.checkOnlineStatus()
  },
  
  onHide() {
    this.clearTypingTimer()
  },
  
		methods: {
    // 初始化聊天
    async initChat() {
      try {
        console.log('开始初始化聊天...')
        
        // 首先测试API连接
        console.log('测试API连接...')
        try {
          const testRes = await customerServiceApi.test()
          console.log('API测试结果:', testRes)
        } catch (error) {
          console.error('API测试失败:', error)
          uni.showToast({
            title: '后端服务未连接，使用测试模式',
            icon: 'none'
          })
        }
        
        // 创建或获取会话ID
        const sessionRes = await customerServiceApi.createSession()
        console.log('创建会话结果:', sessionRes)
        
        if (sessionRes && sessionRes.code === 200) {
          this.sessionId = sessionRes.data.sessionId
          console.log('会话ID:', this.sessionId)
          // 加载历史消息
          this.loadHistoryMessages()
        } else {
          console.error('创建会话失败:', sessionRes)
          // 使用默认会话ID进行测试
          this.sessionId = 'test-session-' + Date.now()
          console.log('使用测试会话ID:', this.sessionId)
        }
      } catch (error) {
        console.error('初始化聊天失败:', error)
        // 使用默认会话ID进行测试
        this.sessionId = 'test-session-' + Date.now()
        console.log('使用测试会话ID:', this.sessionId)
        uni.showToast({
          title: '初始化失败，使用测试模式',
          icon: 'none'
        })
      }
    },
    
    // 加载历史消息
    async loadHistoryMessages() {
      if (this.isLoading) return
      
      this.isLoading = true
      try {
        const res = await customerServiceApi.getHistoryMessages({
          sessionId: this.sessionId,
          page: this.page,
          pageSize: this.pageSize
        })
        
        if (res && res.code === 200) {
          const messages = res.data.messages || []
          // 将新消息添加到列表前面
          this.messageList.unshift(...messages.reverse())
          
          if (messages.length < this.pageSize) {
            this.page = 1 // 重置页码
          } else {
            this.page++
          }
        }
      } catch (error) {
        console.error('加载历史消息失败:', error)
      } finally {
        this.isLoading = false
      }
			},
			
			// 发送消息
    async sendMessage() {
      if (!this.canSend) return
      
      const message = {
        id: Date.now(),
        content: this.inputMessage.trim(),
        timestamp: Date.now(),
        isSelf: true,
        type: 'text'
      }
      
      // 添加到消息列表
      this.messageList.push(message)
      this.scrollToBottom()
				
				// 清空输入框
      const messageContent = this.inputMessage
      this.inputMessage = ''
      
      try {
        console.log('发送消息到后端:', {
          sessionId: this.sessionId,
          content: messageContent,
          type: 'text'
        })
        
        // 发送消息到后端
        const res = await customerServiceApi.sendMessage({
          sessionId: this.sessionId,
          content: messageContent,
          type: 'text'
        })
        
        console.log('发送消息结果:', res)
        
        if (res && res.code === 200) {
          // 更新消息状态
          message.id = res.data.messageId
          message.status = 'sent'
				
				// 模拟客服回复
          this.simulateServiceReply(messageContent)
        } else {
          message.status = 'failed'
          console.error('发送消息失败:', res)
          uni.showToast({
            title: '发送失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('发送消息失败:', error)
        message.status = 'failed'
        uni.showToast({
          title: '发送失败',
          icon: 'none'
        })
        
        // 即使发送失败，也显示模拟回复，让用户知道系统在工作
        this.simulateServiceReply(messageContent)
      }
    },
    
    // 模拟客服回复（实际项目中应该通过WebSocket或轮询获取）
    async simulateServiceReply(userMessage) {
      // 显示输入提示
      this.isTyping = true
      
      // 直接使用本地预存回复，跳过AI调用
      console.log('使用本地预存回复服务...')
      this.showLocalAIReply(userMessage)
    },
    
    // 显示本地AI回复
    showLocalAIReply(userMessage) {
      setTimeout(() => {
        this.isTyping = false
        
        // 直接使用关键词匹配逻辑
        let reply = this.getReplyByKeywords(userMessage)
        
        const replyMessage = {
          id: Date.now(),
          content: reply,
          timestamp: Date.now(),
          isSelf: false,
          type: 'text',
          status: 'sent'
        }
        
        this.messageList.push(replyMessage)
        this.scrollToBottom()
      }, 1000)
    },
    
    // 关键词匹配回复
    getReplyByKeywords(userMessage) {
      const message = userMessage.toLowerCase()
      
      // 订单相关
      if (message.includes('订单') || message.includes('下单')) {
        return '您好，关于订单问题，请提供订单号，我会为您查询详细信息。'
      }
      
      // 退款相关
      if (message.includes('退款') || message.includes('退货') || message.includes('换货')) {
        return '您好，关于退款/退货/换货问题，请提供订单号和具体原因，我们会尽快为您处理。'
      }
      
      // 物流相关
      if (message.includes('物流') || message.includes('发货') || message.includes('配送')) {
        return '您好，关于物流配送问题，请提供订单号，我会为您查询最新物流状态。'
      }
      
      // 优惠券相关
      if (message.includes('优惠券') || message.includes('折扣') || message.includes('活动')) {
        return '您好，目前我们有多种优惠活动，您可以在首页-优惠券中心查看并领取适合的优惠券。'
      }
      
      // 商品相关
      if (message.includes('商品') || message.includes('产品') || message.includes('质量')) {
        return '您好，关于商品问题，请提供商品名称和具体问题描述，我会为您详细解答。'
      }
      
      // 账户相关
      if (message.includes('账户') || message.includes('登录') || message.includes('密码')) {
        return '您好，关于账户问题，请提供您的用户名或手机号，我会协助您解决。'
      }
      
      // 默认回复
      const defaultReplies = [
        '您好，我是智能客服助手，很高兴为您服务！请问有什么可以帮助您的？',
        '感谢您的咨询，我会尽力为您提供帮助。请详细描述您的问题。',
        '您好，我是您的专属客服助手，请问有什么需要帮助的吗？',
        '感谢您的耐心等待，我会尽快为您解答问题。'
      ]
      
      return defaultReplies[Math.floor(Math.random() * defaultReplies.length)]
    },
    
    // 显示默认回复
    showDefaultReply() {
      setTimeout(() => {
        this.isTyping = false
        const defaultReplies = [
          '您好，我是智能客服助手，很高兴为您服务！',
          '我理解您的问题，让我为您详细解答。',
          '感谢您的咨询，还有其他问题需要帮助吗？',
          '我会尽快处理您的问题，请稍等片刻。'
        ]
        
        const randomReply = defaultReplies[Math.floor(Math.random() * defaultReplies.length)]
        const replyMessage = {
          id: Date.now(),
          content: randomReply,
          timestamp: Date.now(),
          isSelf: false,
          type: 'text',
          status: 'sent'
        }
        
        this.messageList.push(replyMessage)
        this.scrollToBottom()
      }, 1000)
			},
			
			// 滚动到底部
			scrollToBottom() {
      this.$nextTick(() => {
        if (this.messageList.length > 0) {
          const lastMessage = this.messageList[this.messageList.length - 1]
          this.scrollIntoView = `msg-${lastMessage.id}`
        }
      })
			},
			
			// 加载更多消息
			loadMoreMessages() {
      if (!this.isLoading && this.page > 1) {
        this.loadHistoryMessages()
      }
    },
    
    // 检查在线状态
    async checkOnlineStatus() {
      try {
        console.log('检查在线状态...')
        const res = await customerServiceApi.checkOnlineStatus()
        console.log('在线状态检查结果:', res)
        this.isOnline = res && res.code === 200 && res.data && res.data.status === 'online'
      } catch (error) {
        console.error('检查在线状态失败:', error)
        // 如果检查失败，默认设置为在线状态，让用户可以尝试发送消息
        this.isOnline = true
        console.log('设置默认在线状态')
      }
    },
    
    // 输入事件
    onInput() {
      // 清除之前的定时器
      this.clearTypingTimer()
      
      // 设置新的定时器，模拟用户正在输入
      this.typingTimer = setTimeout(() => {
        // 可以在这里发送"正在输入"状态到后端
      }, 1000)
    },
    
    // 清除输入定时器
    clearTypingTimer() {
      if (this.typingTimer) {
        clearTimeout(this.typingTimer)
        this.typingTimer = null
      }
    },
    
    // 显示附件选择
    showAttachment() {
      this.showAttachmentPopup = true
    },
    
    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.uploadImage(res.tempFilePaths[0])
        }
      })
      this.showAttachmentPopup = false
    },
    
    // 选择文件
    chooseFile() {
      // uni-app暂不支持选择文件，可以提示用户
      uni.showToast({
        title: '暂不支持文件上传',
        icon: 'none'
      })
      this.showAttachmentPopup = false
    },
    
    // 上传图片
    async uploadImage(filePath) {
      try {
        const res = await customerServiceApi.uploadImage({
          sessionId: this.sessionId,
          filePath: filePath
        })
        
        if (res && res.code === 200) {
          const imageMessage = {
            id: Date.now(),
            content: res.data.fileUrl || res.data.imageUrl,
            timestamp: Date.now(),
            isSelf: true,
            type: 'image',
            status: 'sent'
          }
          
          this.messageList.push(imageMessage)
          this.scrollToBottom()
        }
      } catch (error) {
        console.error('上传图片失败:', error)
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
      }
    },
    
    // 显示选项
    showOptions() {
      this.showOptionsPopup = true
    },
    
    // 清空聊天记录
    clearHistory() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有聊天记录吗？',
        success: (res) => {
          if (res.confirm) {
            this.messageList = []
            this.page = 1
            uni.showToast({
              title: '已清空',
              icon: 'success'
            })
          }
        }
      })
      this.showOptionsPopup = false
    },
    
    // 导出聊天记录
    exportChat() {
      uni.showToast({
        title: '功能开发中',
        icon: 'none'
      })
      this.showOptionsPopup = false
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
      }
			}
		}
	}
</script>

<style lang="scss" scoped>
.customer-service {
  height: 100vh;
  background-color: #f5f5f5;
	display: flex;
	flex-direction: column;
}
	
	.custom-navbar {
  height: 88rpx;
  background-color: #ffffff;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
  position: relative;
  z-index: 100;
}

.navbar-left, .navbar-right {
			width: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

.navbar-center {
  flex: 1;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}
		
		.navbar-title {
			font-size: 32rpx;
			font-weight: 500;
			color: #333;
  line-height: 1.2;
}

.navbar-status {
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
  
  &.online {
    color: #52c41a;
  }
}

.chat-container {
		flex: 1;
		padding: 20rpx;
		overflow-y: auto;
}

.loading-tip {
				display: flex;
				align-items: center;
				justify-content: center;
  padding: 20rpx;
  color: #999;
  font-size: 24rpx;
  
  text {
    margin-left: 10rpx;
  }
}

.message-list {
  padding-bottom: 20rpx;
}

			.message-item {
				display: flex;
				margin-bottom: 30rpx;
				
				&.message-self {
					flex-direction: row-reverse;
					
					.message-content {
						align-items: flex-end;
    }
						
						.message-bubble {
      background-color: #007AFF;
      color: #ffffff;
      border-radius: 20rpx 4rpx 20rpx 20rpx;
    }
  }
}

				.avatar {
  width: 80rpx;
  height: 80rpx;
					margin: 0 20rpx;
  flex-shrink: 0;
}

.avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

				.message-content {
  flex: 1;
					display: flex;
					flex-direction: column;
  align-items: flex-start;
  max-width: 60%;
}

					.message-bubble {
  background-color: #ffffff;
  padding: 20rpx 24rpx;
  border-radius: 4rpx 20rpx 20rpx 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  word-break: break-all;
}
						
						.message-text {
							font-size: 28rpx;
							color: #333;
  line-height: 1.4;
					}
					
					.message-time {
  font-size: 22rpx;
  color: #999;
						margin-top: 10rpx;
}
						
.typing-indicator {
  text-align: center;
  padding: 20rpx;
  color: #999;
							font-size: 24rpx;
}

.input-area {
  background-color: #ffffff;
  border-top: 1rpx solid #e5e5e5;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.input-container {
		display: flex;
		align-items: center;
  background-color: #f8f8f8;
  border-radius: 40rpx;
			padding: 0 20rpx;
}
			
			.message-input {
  flex: 1;
  height: 80rpx;
				font-size: 28rpx;
				color: #333;
  background: transparent;
		}
		
.input-actions {
			display: flex;
			align-items: center;
}

.action-btn {
  width: 60rpx;
  height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
  margin-right: 20rpx;
}

.send-btn {
  background-color: #007AFF;
  color: #ffffff;
  padding: 16rpx 32rpx;
  border-radius: 30rpx;
				font-size: 28rpx;
  font-weight: 500;
  
  &.disabled {
    background-color: #cccccc;
  }
}

.attachment-popup, .options-popup {
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 40rpx 30rpx;
  padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
}

.attachment-title {
  text-align: center;
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 40rpx;
}

.attachment-options {
  display: flex;
  justify-content: space-around;
  margin-bottom: 40rpx;
}

.attachment-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  
  text {
    margin-top: 20rpx;
    font-size: 26rpx;
    color: #666;
  }
}

.attachment-cancel {
  text-align: center;
  padding: 30rpx;
  border-top: 1rpx solid #e5e5e5;
  color: #999;
  font-size: 30rpx;
}

.options-popup {
  padding: 0;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
  
  text {
    margin-left: 20rpx;
    font-size: 30rpx;
    color: #333;
  }
  
  &:last-child {
    border-bottom: none;
    color: #999;
	}
}
</style>